//
//  RetainCountViewController.m
//  ExerciseOC
//
//  Created by 王子曦 on 2025/4/14.
//

#import "RetainCountViewController.h"

@interface RetainCountViewController ()
@property (nonatomic, strong) UITextView *textView;
@end

@implementation RetainCountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"引用计数";
    
    // 创建文本视图
    self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.textView];
    
    // 设置内容
    NSMutableString *content = [NSMutableString string];
    [content appendString:@"引用计数（Reference Counting）是iOS中的内存管理机制\n\n"];
    
    [content appendString:@"1. 引用计数的基本概念：\n"];
    [content appendString:@"   - 每个对象都有一个引用计数器\n"];
    [content appendString:@"   - 当引用计数为0时，对象被释放\n"];
    [content appendString:@"   - 通过retain增加引用计数\n"];
    [content appendString:@"   - 通过release减少引用计数\n\n"];
    
    [content appendString:@"2. MRC下的内存管理：\n"];
    [content appendString:@"   Person *person = [[Person alloc] init];  // count = 1\n"];
    [content appendString:@"   [person retain];  // count = 2\n"];
    [content appendString:@"   [person release];  // count = 1\n"];
    [content appendString:@"   [person release];  // count = 0，对象被释放\n\n"];
    
    [content appendString:@"3. ARC下的引用计数：\n"];
    [content appendString:@"   - 编译器自动管理引用计数\n"];
    [content appendString:@"   - strong修饰符会增加引用计数\n"];
    [content appendString:@"   - weak修饰符不会增加引用计数\n"];
    [content appendString:@"   - 赋值nil会自动减少引用计数\n\n"];
    
    [content appendString:@"4. 引用计数的注意事项：\n"];
    [content appendString:@"   - MRC中retain和release必须配对\n"];
    [content appendString:@"   - 过度retain会导致内存泄漏\n"];
    [content appendString:@"   - 过度release会导致野指针\n"];
    [content appendString:@"   - autorelease可以延迟释放对象\n\n"];
    
    [content appendString:@"5. 调试技巧：\n"];
    [content appendString:@"   - 使用Instruments检测内存泄漏\n"];
    [content appendString:@"   - 使用NSLog打印引用计数\n"];
    [content appendString:@"   - 使用僵尸对象检测过度释放"];
    
    self.textView.text = content;
}

@end